package com.credithc.fastdfs.monitor.util;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class NumUtil {
	/**
	 * 转换为BigDecimal
	 * 
	 * @param o
	 * @return BigDecimal
	 * @author fantasy
	 * @date 2013-8-27
	 */
	public static BigDecimal toBig(Object o) {
		if (o == null || o.toString().equals("") || o.toString().equals("NaN")) {
			return new BigDecimal(0);
		}
		return new BigDecimal(o.toString());
	}

	/**
	 * 计算百分比
	 * 
	 * @param divisor
	 * @param dividend
	 * @return String
	 * @author fantasy
	 * @date 2013-8-27
	 */
	public static String getPercent(Object divisor, Object dividend) {
		if (divisor == null || dividend == null) {
			return "";
		}
		NumberFormat percent = NumberFormat.getPercentInstance();
		// 建立百分比格式化引用
		percent.setMaximumFractionDigits(2);
		BigDecimal a = toBig(divisor);
		BigDecimal b = toBig(dividend);
		if (a.equals(toBig(0)) || b.equals(toBig(0)) || a.equals(toBig(0.0)) || b.equals(toBig(0.0))) {
			return "0.00%";
		}
		BigDecimal c = a.divide(b, 4, BigDecimal.ROUND_DOWN);
		return percent.format(c);
	}

	/**
	 * 计算比例
	 * 
	 * @param divisor
	 * @param dividend
	 * @return String
	 * @author fantasy
	 * @date 2013-10-9
	 */
	public static String divideNumber(Object divisor, Object dividend) {
		if (divisor == null || dividend == null) {
			return "";
		}
		BigDecimal a = toBig(divisor);
		BigDecimal b = toBig(dividend);
		if (a.equals(toBig(0)) || b.equals(toBig(0))) {
			return "0";
		}
		BigDecimal c = a.divide(b, 2, BigDecimal.ROUND_DOWN);
		return c.toString();
	}

	/**
	 * 去两个数的平均值，四舍五入
	 * 
	 * @param divisor
	 * @param dividend
	 * @return int
	 * @author fantasy
	 * @date 2013-11-6
	 */
	public static int averageNumber(Object divisor, Object dividend) {
		if (divisor == null || dividend == null) {
			return 0;
		}
		BigDecimal a = toBig(divisor);
		BigDecimal b = toBig(dividend);
		if (a.equals(toBig(0)) || b.equals(toBig(0))) {
			return 0;
		}
		BigDecimal c = a.divide(b, 0, BigDecimal.ROUND_HALF_UP);
		return c.intValue();
	}

	/**
	 * 根据长度转成kb(千字节)和mb(兆字节)
	 * 
	 * @param bytes
	 * @return
	 */
	public static String bytes2KB(long bytes) {
		BigDecimal filesize = new BigDecimal(bytes);
		BigDecimal megabyte = new BigDecimal(1024 * 1024);
		float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP).floatValue();
		if (returnValue > 1)
			return (returnValue + "MB");
		BigDecimal kilobyte = new BigDecimal(1024);
		returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP).floatValue();
		return (returnValue + "KB");
	}
	
	/** 
	 * @Title: transByteToMB 
	 * @Description: 强制转MB 保留两位小数
	 * @param 
	 * @return long
	 * @throws 
	 */ 
	public static double transByteToMB(long bytes) {
//		return bytes > 0 ? bytes >> 20 : 0;
		DecimalFormat df2  = new DecimalFormat("###.00");
		return bytes > 0 ? Double.valueOf(df2.format((double)(bytes / (1024.0 * 1024.0)))) : 0;
	}
}